﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace weiqijiance.灯光仪
{
    public class NH6108 : libass
    {
        public override bool openCOM(string sSet)
        {
            bool breturn = true;
            try
            {
                base.openCOM(sSet);
                comLI.ReadTimeout = 500;
                comLI.DataReceived += comLI_DataReceived;
            }
            catch
            {
                breturn = false;
            }
            return breturn;
        }

        public override bool sendLIcom(int cmd)//发送指令给灯光仪串口
        {
            bool flag = true;

            try
            {
                switch (cmd)
                {
                    case 3: { sendcmd(0x44); break; }     // 3:二灯制;
                    case 4: { sendcmd(0x46); break; }     // 4:四灯制;
                    case 8: { sendcmd(0x43); break; }     // 8:单测远光
                    case 9: { sendcmd(0x5A); break; }     // 8:左灯全自动检测
                    case 10: { sendcmd(0x59); break; }     // 8:右灯全自动检测
                    case 11: { sendcmd(0x4d);  break;}    // 11:取左主灯数据;
                    case 12: { sendcmd(0x4e); break; }    // 12:取右主灯数据
                }

            }
            catch
            {
                flag = false;
            }
            return flag;
        }
        public bool sendcmd(byte cmd)//发送指令给灯光仪串口
        {
            bool flag = true;
            try
            {
                if (comLI.IsOpen)
                {
                    Byte[] m_byte = new Byte[1];
                    m_byte[0] = cmd;
                    comLI.Write(m_byte, 0, 1);
                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        //灯光 返回数据
        void comLI_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(500);
            int n = comLI.BytesToRead;
            byte[] buf = new byte[n];
            comLI.Read(buf, 0, n);
            if (n > 33)//取数
            {
                if (buf[0] == 0x01 )
                {
                    string data = Encoding.Default.GetString(buf);
                    int.TryParse(data.Substring(12, 4), out iLIGQ);
                    iLIGQ = iLIGQ * 10;
                    bqushu = true;
                }
            }
            else
            {
                if (buf[0] == 0x4F)//主远测量结束
                {
                    byuanguang = true;
                    bjingguang = true;
                }
                else if (buf[0] == 0x52)
                {
                    btuichu = true;
                }

            }
        }
    }
}
